package com.qy.changemachine

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.app.custom.CustomManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.RemoteException
import androidx.core.app.NotificationCompat
import com.android.tdconfig.SuBack
import com.android.tdconfig.SuCall
import com.android.tools.Back
import com.android.tools.Call
import com.google.gson.Gson
import com.qy.changemachine.api.RetrofitClient
import com.qy.changemachine.callBack.ActionCallBack
import com.qy.changemachine.dataBean.DeviceInfoResponse
import com.qy.changemachine.dataBean.InitRequest
import com.qy.changemachine.dataBean.InitResponse
import com.qy.changemachine.dataBean.ResponseData
import com.qy.changemachine.dataBean.StartModuleAction
import com.qy.changemachine.dataBean.TaskResponse
import com.qy.changemachine.dataBean.TaskScriptBean
import com.qy.changemachine.dataBean.UpdateInfoResponse
import com.qy.changemachine.dataBean.XPAction
import com.qy.changemachine.mqtt.MqttManager
import com.qy.changemachine.util.Contants
import com.qy.changemachine.util.LogUtil
import com.qy.changemachine.util.NetworkUtils
import com.qy.changemachine.util.ShellUtils
import com.qy.changemachine.util.Utils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken
import org.eclipse.paho.client.mqttv3.MqttCallback
import org.eclipse.paho.client.mqttv3.MqttMessage
import java.io.File
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit


class MqttForegroundService : Service(), ActionCallBack {
    companion object {
        private const val TAG = "MqttForegroundService"
        private const val CHANNEL_ID = "ForegroundServiceChannel"
    }

    private var initSuFuture: CompletableFuture<Int>? = null
    private var initAutoJsFuture: CompletableFuture<Int>? = null
    private var callXpFuture: CompletableFuture<Int>? = null
    private lateinit var initRequestData: InitRequest
    private val serviceJob = Job()
    private lateinit var utils: Utils
    private lateinit var aidlCall: Call
    private lateinit var suAidlCall: SuCall
    private val serviceScope = CoroutineScope(Dispatchers.IO + serviceJob)
    private var scheduledExecutorService: ScheduledExecutorService? = null
    private var executorService: ExecutorService? = null
    private var mqttManager: MqttManager? = null
    private lateinit var context: Context
    private var taskScriptBean = TaskScriptBean()
    private lateinit var response: InitResponse
    private lateinit var changPhoneResponse: DeviceInfoResponse
    private lateinit var updateInfoResponse: UpdateInfoResponse
    private var customManager: CustomManager? = null


    @SuppressLint("ForegroundServiceType")
    override fun onCreate() {
        super.onCreate()
        LogUtil.init(this) // 初始化 LogUtil
        LogUtil.d(TAG, "Foreground service created current ip:" + NetworkUtils.getIpAddress())
//        SystemPropertiesReflector.set("1.fakeuid", Contants.FAKE_UID)
        customManager = getSystemService("custommanager") as CustomManager
        context = this
        utils = Utils(this, this)
        utils.setAccessibility(this)
        utils.openNtp(context)
        utils.closeBluetooth()
        // 创建通知渠道（Android 8.0 及以上需要）
        createNotificationChannel()

        // 启动前台服务
        val notification = createNotification()
        startForeground(1, notification)

        // 初始化线程池
        executorService = Executors.newSingleThreadExecutor()
        // 创建定时任务执行器
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor()


        serviceScope.launch {
            initRequestData = InitRequest(cloudCode = utils.getImei())
            LogUtil.d(
                TAG,
                "-----step一 initRequestData--version 20250514-------------:" + initRequestData.cloudCode
            )
            //@@@@@@@@@@ step 1  检测网络取云机 信息@@@@@@@@@
            var isSuccess = false
            while (!isSuccess) {
                try {
                    while (!NetworkUtils.isNetworkConnected(context)) {
                        try {
                            // 没网 每隔 2 秒检查一次
                            Thread.sleep(2000)
                            LogUtil.d(TAG, "Network is not Connected sleep 2s and try again!!!!")
                        } catch (e: Exception) {
                            LogUtil.d(TAG, "Network get status Exception: ${e.message}")
                        }
                    }
                    LogUtil.d(TAG, "-----step一 0 start getUpdateInfo---------------------")
                    updateInfoResponse = RetrofitClient.apiService.getUpdateInfo()
                    updateInfoResponse.data?.let { utils.setSystemTime(context, it.timestamp) }
                    LogUtil.d("TAG", "updateInfo Response: ${updateInfoResponse.data}")
                    LogUtil.d(TAG, "-----step一 1 start initPhone-----------------------")
                    response = RetrofitClient.apiService.initPhone(initRequestData)
                    LogUtil.d("TAG", "initPhone Response: ${response.data}")
                    if (response.code != Contants.SucCode) {
                        // 返回非200 每隔 2 秒检查一次 一直要到200 才行
                        Thread.sleep(2000)
                        LogUtil.d(TAG, "-----step一 1 start initPhone code not 200 --------")
                    } else {
                        isSuccess = true
                    }
                } catch (e: Exception) {
                    LogUtil.e("TAG", "Network request failed:${e.message} SLEEP 2s TRY AGAIN")
                    // 有网连不上接口 每隔 2 秒重请求一次
                    Thread.sleep(2000)
                }
            }
            //@@@@@@@@@@ step 2  初始化MQTT @@@@@@@@@@@@@@@
            LogUtil.d(TAG, "-----step二 0 start initMqtt-----------------------")
            if (response.data != null) {
                initMqtt(response.data)
            }

            //@@@@@@@@@@ step 4  初始化相关环境 @@@@@@@@@@@@@@@
            try {
                LogUtil.d(TAG, "-----step四 start init env-----------------------")
                LogUtil.d(TAG, "-----step四 0 init auto js aidl------------------")

                LogUtil.d(TAG, "-----step四 1 copy su apk------------------------")
                utils.copyFileToSDCard(R.raw.su, Contants.KERNEL_SU_APK_NAME)
                LogUtil.d(TAG, "-----step四 2 install su apk---------------------")
                utils.installAppSync(Contants.KERNEL_SU_DOWNLOAD_PATH)
                LogUtil.d(TAG, "-----step四 3 copy vpn apk------------------------")
                utils.copyFileToSDCard(R.raw.vpn, Contants.VPN_APK_NAME)
                LogUtil.d(TAG, "-----step四 3.5 copy nouse apk------------------------")
                utils.copyFileToSDCard(R.raw.nouse, Contants.NO_USE_APK_NAME)
                LogUtil.d(TAG, "-----step四 3.6 copy push apk------------------------")
                utils.copyFileToSDCard(R.raw.push, Contants.PUSH_APK_NAME)
                LogUtil.d(TAG, "-----step四 3.7 copy autojs apk------------------------")
                utils.copyFileToSDCard(R.raw.autojs, Contants.AUTO_JS_APK_NAME)
                utils.installAppSync(Contants.DATA_PATH+Contants.AUTO_JS_APK_NAME)
                LogUtil.d(TAG, "-----step四 4 init SuAidl apk---------------------")
                initSuAidl()
                val initAuto = initAutoJsAidl()
                if (!initAuto || initAutoJsFuture!!.get() != Contants.SucCode) {
                    LogUtil.d(TAG, "-----step四 4.1 init auto js aidl fail stop task-------------")
                }
                if (initSuFuture!!.get() == Contants.SucCode) {
                    LogUtil.d(TAG, "-----step四 5 init  initSuAidl callback already success--")
                } else if (initSuFuture!!.get() == 201) {
                    LogUtil.d(TAG, "-----step四 6 init initSuAidl callback will Success reboot--")
                    val bean = TaskResponse(Contants.WillSucCode, "", "重启中...")
                    if (mqttManager != null) {
                        mqttManager!!.publishMessage(response.data.serverTopic, Gson().toJson(bean))
                    }
                    return@launch
                } else if (initSuFuture!!.get() == Contants.FailCode) {
                    LogUtil.d(TAG, "-----step四 6 init  initSuAidl callback Fail----")
                    return@launch
                }

                while (true) { // 无限循环
                    Thread.sleep(2000)
                    LogUtil.d(TAG, "-----step四 set DNS")
                    if (utils.setDefaultDns()) {
                        LogUtil.d(TAG, "-----step四 7 service init DNS env success over---------")
                        break // 跳出循环
                    } else {
                        LogUtil.d(TAG, "-----step四 7 setDefaultDns fail sleep 2s try again---")
                    }
                }
                val bean = TaskResponse(Contants.SucCode, "", "")
                val ret =
                    mqttManager!!.publishMessage(response.data.serverTopic, Gson().toJson(bean))
                // 当mqtt客户端初始化完成后，跳出循环并发送消息
                LogUtil.d(TAG, "-----step四 8 up load to service  success ret: $ret---------")
                LogUtil.d(TAG, "-----step四 end init env--------------------------")
            } catch (e: Exception) {
                LogUtil.d(TAG, "-----step四 exception init env-----------------------${e.message}")
                return@launch
            }

        }

        LogUtil.d(TAG, "-----step Foreground service oncreate over  ")
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        LogUtil.d(TAG, "Foreground service started")
        return START_STICKY // 服务被系统杀死后会自动重启
    }

    override fun onDestroy() {
        super.onDestroy()
        LogUtil.d(TAG, "Foreground service destroyed")
        // 断开 MQTT 连接
        mqttManager!!.disconnect()
        // 关闭线程池
        if (executorService != null) {
            executorService!!.shutdown()
        }
        // 停止心跳
        stopHeartbeat()
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    private fun initMqtt(data: ResponseData) {
        // 初始化 MQTT 管理器
        mqttManager = MqttManager(
            data.hostUrl,
            data.userName,
            data.pass,
            object : MqttCallback {
                override fun connectionLost(cause: Throwable) {
                    LogUtil.e(TAG, "MQTT connection lost${cause}")
                    // 尝试重新连接
                    reconnectToMqtt()
                }

                override fun messageArrived(topic: String, message: MqttMessage) {
                    val payload = String(message.payload)
                    taskScriptBean = Gson().fromJson(payload, TaskScriptBean::class.java)
                    LogUtil.d(TAG, "Message arrived: $payload and==>:${taskScriptBean.code}")
                    utils.showToast("收到推送消息将要执行: $payload and==>:${taskScriptBean.code}")
                    execServiceAction()
                }

                override fun deliveryComplete(token: IMqttDeliveryToken) {
                    LogUtil.d(TAG, "Message delivered")
                }
            },
            utils.getImei()
        )

        // 在后台线程中连接 MQTT
        executorService!!.execute {
            mqttManager!!.connect()
            // 订阅服务端消息
            mqttManager!!.subscribe(data.topicName)
            //发送心跳到服务端
            startHeartbeat(data.serverTopic)
        }
    }

    private fun createNotificationChannel() {
        val channel = NotificationChannel(
            CHANNEL_ID,
            "Foreground Service Channel",
            NotificationManager.IMPORTANCE_LOW
        )
        val manager = getSystemService(NotificationManager::class.java)
        manager.createNotificationChannel(channel)
    }

    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle(Contants.MQTT_TITLE)
            .setContentText(Contants.MQTT_CONTEXT)
            .setSmallIcon(R.drawable.ic_launcher_foreground) // 替换为你的通知图标
            .setOngoing(true) // 设置通知为持续通知，无法被清除
            .setAllowSystemGeneratedContextualActions(false) // 禁用滑动清除（Android 10+）
            .build()
    }

    private fun reconnectToMqtt() {
        Handler(Looper.getMainLooper()).postDelayed({
            LogUtil.d(TAG, "Reconnecting to MQTT broker...")
            executorService!!.execute {
                mqttManager!!.reconnect()
                if (response != null) {
                    mqttManager!!.subscribe(response.data.topicName)
                }
            }

        }, 2000) //2 秒后重试
    }

    private fun startHeartbeat(topic: String) {
        // 每隔 5 秒发送一次心跳消息
        scheduledExecutorService!!.scheduleWithFixedDelay({
            try {
                mqttManager!!.publishMessage(topic, Contants.MQTT_HEADER_MESSAGE)
                if (mqttManager!!.retryConnectCount >= mqttManager!!.maxRetryConnect) {
                    LogUtil.e(
                        TAG,
                        "MQtt 240 time retry still Failed , factoryReset factoryReset factoryReset"
                    )
                    utils.factoryReset(this)
                }
                if (response != null) {
                    // 重复订阅
                    mqttManager!!.subscribe(response.data.topicName)
                }
            } catch (e: Exception) {
                // 处理异常，例如重试或记录日志
                LogUtil.d(
                    TAG, "startHeartbeat Exception:$e"
                )
            }
        }, 0, 5, TimeUnit.SECONDS)
    }

    private fun stopHeartbeat() {
        // 停止定时任务
        if (scheduledExecutorService != null) {
            scheduledExecutorService!!.shutdown()
        }
    }

    // @@@@@@@@@@@执行 客户端的任务@@@@@@@@@@@@@@@@@@@@
    private fun execServiceAction() {
        //后面会有很多的类型
        when (taskScriptBean.code) {
            TaskScriptBean.DOWNLOAD_JS -> {
                val path = taskScriptBean.filePath
                if (path != null && path != "null") {
                    executorService?.execute {
                        utils.showToast("获取下载脚本任务")
                        LogUtil.d(TAG, "Download Message arrived path :$path")
                        if (path.endsWith(Contants.END_SH)) {
                            Contants.AUTO_JS_PATH = Contants.DATA_PATH + Contants.SH
                        } else {
                            Contants.AUTO_JS_PATH = Contants.DATA_PATH + Contants.JS
                        }
                        LogUtil.d(
                            TAG,
                            "will downLoad Contants.AUTO_JS_PATH:${Contants.AUTO_JS_PATH}"
                        )
                        utils.downLoad(path, Contants.AUTO_JS_PATH, false)
                    }
                } else {
                    LogUtil.e(TAG, "filePath is null, cannot download")
                }
            }

            TaskScriptBean.TASK_STOP -> {
                // 处理停止任务的逻辑
                val volumeChangedIntent = Intent("android.media.VOLUME_CHANGED_ACTION")
                sendBroadcast(volumeChangedIntent)
            }

            TaskScriptBean.CLOUD_RESET -> {
                utils.factoryReset(this)
            }

            TaskScriptBean.DOWNLOAD_OTA -> {
                val path = taskScriptBean.filePath
                if (path != null && path != "null") {
                    executorService?.execute {
                        LogUtil.d(TAG, "Message arrived will DOWNLOAD_OTA")
                        utils.downLoad(path, Contants.OTA_DOWNLOAD_PATH, false)
                        val mess = "OTA下载中..."
                        val bean =
                            TaskResponse(Contants.OTAUpdateIngCode, taskScriptBean.code, mess)
                        mqttManager!!.publishMessage(response.data.serverTopic, Gson().toJson(bean))
                    }
                } else {
                    LogUtil.e(TAG, "filePath is null, cannot download")
                }
            }

            TaskScriptBean.OPEN_STREAM -> {
                utils.installAppSync(Contants.DATA_PATH + Contants.PUSH_APK_NAME)
                utils.startApp(
                    context, Contants.PUSH_APK_PACKAGE,
                    Contants.PUSH_APK_PACKAGE_MAIN_CLASS, Contants.PUSH_APK_KEY, utils.imei
                )
            }

            TaskScriptBean.STOP_STREAM -> {
                utils.uninstall(Contants.PUSH_APK_PACKAGE)
            }

            else -> {
                LogUtil.e(TAG, "未知命令")
            }
        }
    }

    override fun copyFile2SdcardSuccess(name: String) {
        LogUtil.d(TAG, "$name-->copyFile2SdcardSuccess--->step1")
    }

    override fun copyFile2SdcardFail(name: String) {
        val mess = name + "copyFile2SdcardFail"
        LogUtil.d(TAG, mess)
        val bean = TaskResponse(Contants.FailCode, taskScriptBean.code, mess)
        mqttManager!!.publishMessage(response.data.serverTopic, Gson().toJson(bean))
    }

    override fun installSuccess(name: String) {

    }

    override fun installFail(name: String) {
        val mess = "$name-->installFail"
        LogUtil.d(TAG, mess)
        val bean = TaskResponse(Contants.FailCode, taskScriptBean.code, mess)
        mqttManager!!.publishMessage(response.data.serverTopic, Gson().toJson(bean))
    }

    override fun downLoadSuccess(name: String) {
        LogUtil.d(TAG, "downLoadSuccess------>name:" + name)
        if (aidlCall == null) {
            val ret = initAutoJsAidl();
            LogUtil.d(TAG, "aidlCall is null reconect:" + ret);
        }
        val result = ShellUtils.execCommand("chmod 777 $name", true)
        LogUtil.d(TAG, "downLoadSuccess------>ShellUtils.execCommand:$result")
        if (name == Contants.AUTO_JS_PATH) {
            try {
                aidlCall.callDoTask(Contants.AUTO_JS_PATH, object : Back.Stub() {
                    @Throws(RemoteException::class)
                    override fun callDoTaskBack(mess: String) {
                        LogUtil.d(TAG, "callDoTaskBack===========>: $mess")
                        when (mess) {
                            Contants.ExecAutoJsRtSuc -> {
                                val bean = TaskResponse(
                                    Contants.ExecSucCode,
                                    taskScriptBean.taskId,
                                    "脚本成功执行完成"
                                )
                                mqttManager!!.publishMessage(
                                    response.data.serverTopic,
                                    Gson().toJson(bean)
                                )
                            }

                            Contants.ExecAutoJsRtExc -> {
                                val bean = TaskResponse(
                                    Contants.ExecFailCode,
                                    taskScriptBean.taskId,
                                    "脚本异常执行完成"
                                )
                                mqttManager!!.publishMessage(
                                    response.data.serverTopic,
                                    Gson().toJson(bean)
                                )
                            }
                        }
                    }
                })
            } catch (e: Exception) {
                val bean = TaskResponse(
                    Contants.ExecFailCode,
                    taskScriptBean.taskId,
                    "脚本异常执行完成，aidl 无法调用Android tools"
                )
                mqttManager!!.publishMessage(
                    response.data.serverTopic,
                    Gson().toJson(bean)
                )
                LogUtil.d(TAG, "aidlCall.callDoTask excption")
            }
        } else if (name == Contants.OTA_DOWNLOAD_PATH) {
            LogUtil.d(TAG, "OTA包下载成功开始OTA升级")
            val file = File(Contants.OTA_DOWNLOAD_PATH)
            if (!utils.verifyPackageInstallPackage(file)) {
                val mess = "OTA 升级失败文件校验未通过"
                val bean = TaskResponse(Contants.OTAUpdateFailCode, taskScriptBean.code, mess)
                mqttManager!!.publishMessage(response.data.serverTopic, Gson().toJson(bean))
                LogUtil.d(TAG, mess)
                return
            }
//            val ret = utils.otaUpdate(this, Contants.OTA_DOWNLOAD_PATH);
            val ret = utils.otaUpdate(this, file);
            if (ret) {
                val mess = "OTA 升级中..."
                val bean = TaskResponse(Contants.OTAUpdateIngCode, taskScriptBean.code, mess)
                mqttManager!!.publishMessage(response.data.serverTopic, Gson().toJson(bean))
                LogUtil.d(TAG, mess)
            } else {
                val mess = "OTA 升级失败异常"
                val bean = TaskResponse(Contants.OTAUpdateFailCode, taskScriptBean.code, mess)
                mqttManager!!.publishMessage(response.data.serverTopic, Gson().toJson(bean))
                LogUtil.d(TAG, mess)
            }

        }
    }

    override fun downLoadFail(name: String) {
        when {
            name.contains(Contants.AUTO_JS_PATH) -> {
                val mess = "downLoadFail auto js:"
                LogUtil.d(TAG, mess)
                val bean = TaskResponse(Contants.DownLoadFailCode, taskScriptBean.code, mess + name)
                mqttManager!!.publishMessage(response.data.serverTopic, Gson().toJson(bean))
            }

            name.contains(Contants.OTA_DOWNLOAD_PATH) -> {
                val mess = "downLoadFail ota :"
                LogUtil.d(TAG, mess)
                val bean =
                    TaskResponse(Contants.DownLoadOTAFailCode, taskScriptBean.code, mess + name)
                mqttManager!!.publishMessage(response.data.serverTopic, Gson().toJson(bean))
            }
        }
    }


    private val connection = object : ServiceConnection {
        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            aidlCall = Call.Stub.asInterface(service)
            LogUtil.d(TAG, "auto js 初始化链接 连接成功")
            initAutoJsFuture!!.complete(Contants.SucCode)
        }

        override fun onServiceDisconnected(className: ComponentName) {
            LogUtil.d(TAG, "auto js 初始化链接 连接断开")
        }
    }

    private fun initAutoJsAidl(): Boolean {
        initAutoJsFuture = CompletableFuture<Int>()
        val intent = Intent()
        intent.setAction(Contants.AUTO_JS_AIDL_ACTION)
        intent.setPackage(Contants.AUTO_JS_PACKAGE_NAME)
        val executor = Executors.newSingleThreadExecutor()
        val re = bindService(intent, Context.BIND_AUTO_CREATE, executor, connection)
        LogUtil.i(TAG, if (re) "成功绑定AutoJs服务" else "失败绑定AutoJs服务")
        return re
    }

    private val suConnection = object : ServiceConnection {
        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            try {
                suAidlCall = SuCall.Stub.asInterface(service)
                LogUtil.d(TAG, "Su  连接成功开始调用----------")
                suAidlCall.callDoTask("", object : SuBack.Stub() {
                    override fun callDoTaskBack(aString: String?, code: Int) {
                        when (code) {
                            Contants.SucCode -> {
                                LogUtil.d(
                                    TAG,
                                    "Su  连接成功 callback Contants.SucCode Su环境初始化完成"
                                )
                            }

                            Contants.WillSucCode -> {
                                val msg = "Su  连接成功 callback 201 XP 安装完成即将重启"
                                LogUtil.d(TAG, msg)
                                val bean = TaskResponse(Contants.WillSucCode, "", msg)
                                mqttManager?.publishMessage(
                                    response.data.serverTopic,
                                    Gson().toJson(bean)
                                )
                            }

                            Contants.FailCode -> {
                                val bean = TaskResponse(Contants.FailCode, "", "install xp fail")
                                mqttManager?.publishMessage(
                                    response.data.serverTopic,
                                    Gson().toJson(bean)
                                )
                                LogUtil.d(
                                    TAG,
                                    "Su  连接成功 callback Contants.FailCode install xp fail 任务终止"
                                )
                            }
                        }
                        initSuFuture!!.complete(code)
                    }
                })
            } catch (e: RemoteException) {
                val bean = TaskResponse(Contants.FailCode, "", "call back xp exception")
                mqttManager?.publishMessage(
                    response.data.serverTopic,
                    Gson().toJson(bean)
                )
                LogUtil.d(
                    TAG,
                    "Su  连接成功 callback Contants.FailCode install xp fail 任务终止${e.message}"
                )
            }


        }

        override fun onServiceDisconnected(className: ComponentName) {
            LogUtil.d(TAG, "Su  连接断开")
        }
    }

    private fun initSuAidl(): Boolean {
        initSuFuture = CompletableFuture<Int>()
        val intent = Intent()
        intent.setAction(Contants.KERNEL_SU_AIDL_ACTION)
        intent.setComponent(
            ComponentName(
                Contants.KERNEL_SU_PACKAGE_NAME,
                Contants.KERNEL_SU_SERVICE_NAME
            )
        )
        val re = bindService(intent, suConnection, Context.BIND_AUTO_CREATE);
        LogUtil.e(TAG, if (re) "绑定 su 服务 成功" else "绑定 su 服务 失败")
        return re
    }

    private fun initCallXp() {
        val startModuleAction = StartModuleAction()
        val xpAction = XPAction(jsonData = startModuleAction)
        val xpActionJson = Gson().toJson(xpAction)
        LogUtil.d(TAG, "initCallXp json:${xpActionJson}")
        suAidlCall.callDoTask(xpActionJson, object : SuBack.Stub() {
            override fun callDoTaskBack(aString: String?, code: Int) {
                when (code) {
                    Contants.SucCode -> {
                        LogUtil.d(TAG, "initCallXp 回调 成功 ")
                    }

                    Contants.FailCode -> {
                        LogUtil.d(TAG, "initCallXp 回调 失败 ")
                    }
                }
                callXpFuture?.complete(code)
            }
        })
        callXpFuture = CompletableFuture<Int>()
    }

}